package com.yunyike.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.model.User;
import com.yunyike.redis.JedisManager;
import com.yunyike.response.Response;
import com.yunyike.utils.CookieUtils;
import com.yunyike.utils.JsonUtils;

public class BaseController extends MultiActionController {

	private static Logger log = LoggerFactory.getLogger(BaseController.class);
	
	protected HttpServletRequest request;
	
	/**
	 * 获取当前登录的用户
	 * @return
	 */
	protected User getCurrentUser() {
		// 获取用户的cookie
		Cookie cookie = CookieUtils.getCookie(getRequest(), CommonConstant.USER_KEY_COOKIE);
		
		if(cookie == null || StringUtils.isBlank(cookie.getValue())){
			return null;
		}
		
		// 根据cookie值获取用户
		User user = (User)JedisManager.getObject(cookie.getValue());
		
		if(user == null){
			return null;
		}
		
		log.info("----->>current user:"+user);
		
		return user;
	}

	protected void returnDatas(Response result, HttpServletResponse response){
		
		String objectAsString = JsonUtils.ObjectAsString(result);
		
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter writer;
		try {
			writer = response.getWriter();
			writer.write(objectAsString);
		} catch (Exception e) {
			log.info("----->>returnDatas has error:",e.getMessage(),e);
		}
	}
	
	public HttpServletRequest getRequest() {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		this.request = ((ServletRequestAttributes) ra).getRequest();
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	/**
	 * 验证请求参数
	 * @param br
	 */
	public void checkRequest(BindingResult br,Response res,HttpServletResponse response){
		if(br.hasErrors()){
			
			List<String> errorList = new ArrayList<String>();
			
			List<FieldError> fieldErrors = br.getFieldErrors();
			logger.info("==========start to print error message...===========");
			for(FieldError oe : fieldErrors){
				String field = oe.getField();
				String message = oe.getDefaultMessage();
				errorList.add(field+":"+message);
				logger.info(field+message);
			}
			logger.info("==========end to print error message=================");
			
			
			res.getResult().setCode(CommonConstant.NUMBER__2);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__2));
			returnDatas(res, response);
		}
	}
	
}
